<template>
  <input
    v-model="formatValue"
    class="form-input"
    type="text"
  />
</template>

<script>

const formatFn = {
  /**
   * 13683599380
   * @return 136 8359 9380
   */
  phone: (val) => {
    let newValue = val.substr(0, 11)
    const reg = /(\d{1,})(\d{4})/
    while (reg.test(newValue)) {
      newValue = newValue.replace(reg, '$1 $2')
    }
    return newValue
  },
  idCard: (val) => {},
  bankNo: (val) => {},
  money: (val) => {}
}

const clearFormat = (val) => {
  return val.replace(/\s+/g, '')
}

export default {
  name: 'BwInput',
  props: {
    value: {
      type: String,
      default: 'text'
    },
    type: {
      type: String,
      default: 'text'
    }
  },
  data () {
    return {
      val: this.value
    }
  },
  watch: {
    value (newValue) {
      this.val = newValue
    },
    val (newValue) {
      this.$emit('input', newValue)
    }
  },
  computed: {
    formatValue: {
      get () {
        const updateFn = formatFn[this.type]
        return updateFn ? updateFn(this.val) : this.val
      },
      set (newValue) {
        this.val = clearFormat(newValue, this.type)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-input {
  @include wh(100%, 100px);
  background: transparent;
  border: 0;
  outline: none;
  line-height: 100px;
  padding: 0 20px;
  box-sizing: border-box;
}
</style>
